<template>
  <div class="app-closed-task">
    <v-data-table
      :headers="headers"
      item-key="group"
      :items="collect"
      class="elevation-1"
      hide-default-footer
      hide-default-header
      :items-per-page="100"
      no-data-text="无数据"
    >
      <template v-slot:item.lastediteddate="{ item }">
        <div class="lastediteddate" v-if="Object.is(item.group, '其他')">
          <span>其他</span>
        </div>
        <div class="lastediteddate" v-else>
          <span class="mr-1">{{ dateFormat(item.group, "date") }}</span>
          <span>{{ dateFormat(item.group, "week") }}</span>
        </div>
      </template>
      <template v-slot:item.taskItem="{ item }">
        <span style="font-size:12px;color:#777">清单外任务</span>
        <div v-for="task in item.children" :key="task.id" class="mt-1 mb-1">
          <v-icon
            :color="task.status == 'closed' ? 'green' : 'red'"
            size="16"
            class="mr-2"
            v-text="task.status == 'closed' ? 'mdi-check' : 'mdi-close'"
          ></v-icon>
          <span class="mr-2 taskname" @click="toTaskDetails(task)">{{
            task.name
          }}</span>

          <span style="font-size:12px;color:#777">{{
            getUserName(task.lasteditedby)
          }}</span>
        </div>
      </template>
    </v-data-table>
  </div>
</template>

<script lang="ts">
import {
  Vue,
  Component,
  Prop,
  Model,
  Emit,
  Watch,
  Provide,
} from "vue-property-decorator";

import "./app-closed-task.less";
import ProjectService from "@/service/project/project-service";
import UsersService from "@/service/user/user-service";
import CodeListService from "@/codelist/codelist-service";
import ProjectTeamServiceBase from "@service/project-team/project-team-service-base";

@Component({})
export default class AppClosedTask extends Vue {
  /**
   * 表格头部
   *
   * @type {any}
   * @memberof AppClosedTask
   */
  public headers: any = [
    { text: "最后修改时间", value: "lastediteddate" },
    { text: "任务列表", value: "taskItem" },
  ];

  public collect: any = [];
  /**
   * 应用上下文
   *
   * @type {*}
   * @memberof AppClosedTask
   */
  @Prop() public context: any;

  /**
   * 所有列成员
   *
   * @type {*}
   * @memberof AppClosedTask
   */
  @Prop() public allColumns: any;

  /**
   * 所选成员
   *
   * @type {any}
   * @memberof AppClosedTask
   */
  public lasteditedby: any = "";

  /**
   * 数据集
   *
   * @type {any}
   * @memberof AppClosedTask
   */
  @Prop() public items: any;

  /**
   * 代码表服务对象
   *
   * @type {CodeListService}
   * @memberof AppClosedTask
   */
  public codeListService: CodeListService = new CodeListService({
    $store: this.$store,
  });

  /**
   * 项目成员清单
   *
   * @type {any}
   * @memberof AppClosedTask
   */
  public taskTeamMemberMetaShow: any = [];

  /**
   * 项目团队对象
   *
   * @type {ProjectTeamServiceBase}
   * @memberof AppClosedTask
   */
  public projectTeamServiceBase: ProjectTeamServiceBase = new ProjectTeamServiceBase();

  /**
   * 全部用户信息
   *
   * @type {any}
   * @memberof AppClosedTask
   */
  public userslist: any = [];

  /**
   *分页对象
   *
   *@memberof AppClosedTask
   */
  private page: any = {
    size: 1000,
    page: 0,
  };

  /**
   * 当前页
   */
  @Prop() public curPage: any;

  /**
   * 分页条数
   *
   * @type {number}
   * @memberof ClosedGridBase
   */
  @Prop() public limit: any;

  /**
   * 总条数
   *
   * @type {number}
   * @memberof ClosedGridBase
   */
  @Prop() public totalrow: any;

  /**
   * 将时间转换成月/日格式
   * @param {any} time
   * @memberof AppClosedTask
   */
  public dateFormat(time: any, type: any) {
    var date = new Date(time);
    if (Object.is(type, "week")) {
      var week;
      if (date.getDay() == 0) week = "周日";
      if (date.getDay() == 1) week = "周一";
      if (date.getDay() == 2) week = "周二";
      if (date.getDay() == 3) week = "周三";
      if (date.getDay() == 4) week = "周四";
      if (date.getDay() == 5) week = "周五";
      if (date.getDay() == 6) week = "周六";
      return week;
    } else if (Object.is(type, "date")) {
      var month = date.getMonth() + 1;
      var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      return month + "/" + day;
    }
  }

  @Watch("items")
  onItemsChange(newVal: any, oldVal: any) {
    if (this.curPage === 1) {
      this.collect = [];
    }
    if (newVal.length > 0) {
      for (let i = 0; i < newVal.length; i++) {
        this.collect.forEach((collectItem: any) => {
          if (newVal[i]) {
            if (Object.is(newVal[i].group, collectItem.group)) {
              newVal[i].children.forEach((valItem: any) => {
                if (
                  JSON.stringify(collectItem.children).indexOf(
                    JSON.stringify(valItem)
                  ) == -1
                ) {
                  collectItem.children.push(valItem);
                }
              });
              newVal.splice(i, 1);
              i--;
            }
          }
        });
      }

      this.collect.push(...newVal);
      //console.log(JSON.stringify(this.collect));
    }
  }

  /**
   * 根据用户名获取中文名
   *
   * @param {any} val
   * @returns {string}
   * @memberof AppClosedTask
   */
  public getUserName(val: any): string {
    let username: any = "";
    this.userslist.forEach((item: any) => {
      if (Object.is(item.value, val)) {
        username = item.label;
      }
    });
    return username;
  }

  /**
   * Vue声明周期，组件创建完毕
   *
   * @memberof AppClosedTask
   */
  public created() {
    this.getCodeList();
  }

  public isCompleted: boolean = false;

  public mounted() {
    let index: any = document.querySelector(".index_view");
    index.addEventListener("scroll", this.btn_pos);
  }

  public btn_pos() {
    this.isCompleted = Math.floor(this.totalrow / this.limit) == this.curPage - 1;
    if (!this.isCompleted) {
      let index: any = document.querySelector(".index_view");
      //变量scrollTop是滚动条滚动时，距离顶部的距离
      var scrollTop = index.scrollTop;
      //变量windowHeight是可视区的高度
      var windowHeight = index.clientHeight;
      //变量scrollHeight是滚动条的总高度
      var scrollHeight = index.scrollHeight;
      //滚动条到底部的条件
      if (scrollHeight - windowHeight == scrollTop) {
        //到了这个就可以进行业务逻辑加载后台数据了
        // _this.footerText = '我是有底线的';
        this.$emit("pageonchange", this.curPage + 1);
      }
    }
  }

  /**
   * 获取动态代码表UserRealName
   *
   * @memberof AppClosedTask
   */
  public async getCodeList() {
    let codeList: any = this.codeListService.getItems("UserRealName");
    await codeList
      .then((items: any) => {
        if (items && items.length > 0) {
          this.userslist.push(...items);
        }
      })
      .catch((error: any) => {
        console.log(error);
      });
    await this.getTaskTeam();
  }

  /**
   * 点击任务跳转到任务详情
   *
   * @param {any} item
   * @memberof AppClosedTask
   */
  public toTaskDetails(item: any) {
    this.$emit("rowdblclick", JSON.parse(JSON.stringify(item)));
  }

  /**
   * 获取项目团队成员清单
   *
   * @memberof AppClosedTask
   */
  public async getTaskTeam() {
    let context: any = {};
    let params: any = {
      srfparentdename: "Project",
      srfparentkey: this.context.project,
      project: this.context.project,
      multiple: 0,
      n_root_eq: this.context.project,
    };

    Object.assign(params, this.page);
    await this.projectTeamServiceBase
      .FetchDefault(context, params, true)
      .then((response: any) => {
        if (response && response.status === 200) {
          if (response.data) {
            let owner = { value: "", label: "所有人" };
            this.taskTeamMemberMetaShow = [];
            this.taskTeamMemberMetaShow.push(owner);
            for (let i = 0; i < response.data.length; i++) {
              let account = response.data[i].account;
              let realname = response.data[i].account;
              let commiter = response.data[i].commiter;
              this.userslist.forEach((useritme: any) => {
                if (Object.is(useritme.value, account)) {
                  realname = useritme.label;
                }
              });
              let member: any = {
                value: account,
                label: realname,
              };

              this.taskTeamMemberMetaShow.push(member);
            }
          }
        }
      })
      .catch((e: any) => {
        if (e && e.status === 500) {
          const url: any = "/500";
          this.$router.push({ path: url });
        } else {
          this.$Notice.error({
            title: "错误",
            desc: e.data.message,
          });
        }
      });
  }

  /**
   * 根据成员进行过滤
   *
   * @memberof AppClosedTask
   */
  public selectMemberChange(val: any) {
    this.$emit("onload", {
      n_lasteditedby_eq: val,
    });
  }
}
</script>
